package com.fusion.exception;

import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class ServiceExceptionHandler {

	@ExceptionHandler(value = Exception.class)
	public ResponseEntity<ResponseData<Object>> defaultErrorHandler(HttpServletResponse response, Exception exception) {
		Integer status = ServiceErrorStatus.REQUEST_ERROR.status();
		String message = ServiceErrorStatus.REQUEST_ERROR.message();
		String describe = exception.getMessage();
		if (exception instanceof ServiceRunTimeException) {
			ServiceRunTimeException httpException = (ServiceRunTimeException) exception;
			Integer serviceStatus = httpException.getStatus();
			if (serviceStatus != null) {
				status = serviceStatus;
			}
			String serviceMessage = httpException.getMessage();
			if (serviceMessage != null && serviceMessage.trim().length() > 0) {
				message = serviceMessage;
			}
			String serviceDescribe = httpException.getDescribe();
			if (serviceDescribe != null && serviceDescribe.trim().length() > 0) {
				describe = serviceDescribe;
			}
			ResponseData<Object> errorMessage = ResponseData.ERROR(status, message, describe);
			return ResponseEntity.status(httpException.getHttpStatus()).body(errorMessage);
		}
		ResponseData<Object> errorMessage = ResponseData.ERROR(status, message, describe);
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorMessage);
	}

}
